<template>
  <div class="wallet-container">
    <ResponsiveNav />
    <div class="header-placeholder"></div>

    <div class="page-content">
      <div class="wallet-page">
        <!-- 面包屑导航区域 -->
        <div class="page-nav">
          <div class="breadcrumb">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item @click="handleBack">
                <i class="fas fa-chevron-left"></i>
                {{ fromAccount ? $t('返回账户') : $t('返回资产') }}
              </el-breadcrumb-item>
              <el-breadcrumb-item>{{ $t('钱包地址管理') }}</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div class="divider"></div>
        </div>

        <!-- 页面标题 -->
        <div class="page-header">
          <h1>{{ $t('钱包地址管理') }}</h1>
          <div class="security-alert">
            <i class="fas fa-shield-alt"></i>
            {{ $t('为了您的资金安全，请仔细核对添加的钱包地址') }}
          </div>
        </div>

        <!-- 添加地址按钮 -->
        <div class="action-bar">
          <el-button
            type="primary"
            v-if="!addresses.length"
            class="amazon-button primary"
            @click="showAddDialog = true"
          >
            <i class="fas fa-plus"></i> {{ $t('添加钱包地址') }}
          </el-button>
        </div>

        <!-- 地址列表 -->
        <div class="address-list">
          <el-empty
            v-if="!addresses.length"
            :image-size="120"
          >
            <template #image>
              <i class="fas fa-wallet empty-icon"></i>
            </template>
            <template #description>
              <p class="empty-text">{{ $t('暂无钱包地址') }}</p>
            </template>
          </el-empty>

          <template v-else>
            <div
              v-for="address in addresses"
              :key="address.id"
              class="address-card"
            >
              <div class="card-header">
                <div class="crypto-info">
                  <!-- <img :src="getCryptoIcon(address.crypto)" :alt="address.crypto" class="crypto-icon"> -->
                  <span class="crypto-name">{{ address.coinName }}</span>
                  <el-tag
                    size="small"
                    :type="address.isDefault ? 'success' : 'info'"
                  >
                    {{ address.isDefault ? $t('默认地址') : $t('普通地址') }}
                  </el-tag>
                </div>
                <div class="actions">
                  <!-- <el-button
                    v-if="!address.isDefault"
                    type="primary"
                    link
                    @click="setDefault(address)"
                  >
                    {{ $t('设为默认') }}
                  </el-button> -->

<!--                  <el-button-->
<!--                    type="danger"-->
<!--                    link-->
<!--                    @click="handleDeleteClick2(address)"-->
<!--                  >-->
<!--                    {{ $t('修改') }}-->
<!--                  </el-button>-->
                  <el-button
                    type="danger"
                    link
                    @click="handleDeleteClick(address)"
                  >
                    {{ $t('删除') }}
                  </el-button>
                </div>
              </div>
              <div class="address-info">
                <div class="network">
                  <span class="label">{{ $t('网络') }}:</span>
                  <span class="value">{{ address.walletInternet }}</span>
                </div>
                <div class="address">
                  <span class="label">{{ $t('地址') }}:</span>
                  <span class="value">
                    <!-- {{ address.walletAddress }} -->
                    **** **** **** {{ address. walletAddress.slice(-4) }}
                  </span>
                  <el-button type="primary" link @click="copyAddress(address.walletAddress)">
                    <i class="far fa-copy"></i>
                  </el-button>
                </div>
                <div class="remark">
                  <span class="label">{{ $t('备注') }}:</span>
                  <span class="value">{{ address.remark || '-' }}</span>
                </div>
              </div>
            </div>
          </template>
        </div>

        <!-- 分页器 -->
        <div class="pagination-wrapper">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :total="total"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>

        <!-- 添加地址对话框 -->
        <AddWalletDialog
          v-model="showAddDialog"
          @success="handleAddSuccess"
        />
        <AddWalletDialogedit
          v-model="showAddDialog2"
          @success="handleAddSuccess2"
          :itemsuccess="itemsuccess"
        />

        <!-- 删除验证弹窗 -->
        <VerifyDialog
          v-model="showDeleteVerify"
          :title="$t('删除钱包地址')"
          :warning-text="$t('删除钱包地址需要验证，请选择验证方式')"
          :confirm-button-text="$t('确认删除')"
          confirm-button-type="danger"
          @confirm="handleDeleteConfirm"
          @cancel="addressToDelete = null"
        />
      </div>
    </div>

    <Footer />
  </div>
</template>

<script setup lang="ts">
import { ref ,onMounted} from 'vue'
import {ElLoading, ElMessage, ElMessageBox} from 'element-plus'
import { useRouter, useRoute } from 'vue-router'
import ResponsiveNav from '@/components/ResponsiveNav.vue'
import Footer from '@/components/Footer.vue'
import AddWalletDialog from '@/components/AddWalletDialog.vue'
import AddWalletDialogedit from '@/components/AddWalletDialogedit.vue'

import VerifyDialog from '@/components/VerifyDialog.vue'

import {  walletAddressUpdate,walletAddressdel, walletAddressAdd ,walletAddresslLst} from '@/api/assets'

import type { WalletAddress } from './types'
import {useI18n} from "vue-i18n";
import {ApiConfirmPay} from "@/api/commodity";
const { t } = useI18n();

const router = useRouter()
const route = useRoute()

// 判断是否从账户页面进入
const fromAccount = ref(route.query.from === 'account')

// 状态变量
const showAddDialog = ref(false)
const itemsuccess = ref({})
const showAddDialog2 = ref(false)
const showDeleteVerify = ref(false)
const addressToDelete = ref<number | null>(null)

// 地址列表
const addresses = ref<WalletAddress[]>([
  // {
  //   id: 1,
  //   crypto: 'USDT',
  //   network: 'TRC20',
  //   address: 'TNPeeaaFB7K9cmo4uQpcU32zGK8G1NYqeL',
  //   remark: '火币提现地址',
  //   isDefault: true
  // }
])
// 分页
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 获取地址列表
const fetchAddresses = async () => {
  try {
    let obj = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
    }
    walletAddresslLst(obj).then(res => {
      addresses.value = res.rows;
      total.value = res.total
    })
  } catch (error) {
    console.error('获取地址列表失败:', error)
  }
}

const handleSizeChange = (val) => {
  pageSize.value = val
  // TODO: 重新加载数据
  fetchAddresses();
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  // TODO: 重新加载数据
  fetchAddresses()
}

// 方法
const setDefault = async (address: WalletAddress): Promise<void> => {
  try {
    // TODO: 调用设置默认地址API
    await new Promise(resolve => setTimeout(resolve, 500))

    ElMessage.success(t('设置成功'))
  } catch (error) {
    console.error('设置失败:', error)
  }
}

const deleteAddress = async (id: number | null, verifyType: string, verifyCode: string): Promise<void> => {
  if (!id) return
  // TODO: 调用删除API
  // console.log('删除地址:', id, '验证方式:', verifyType, '验证码:', verifyCode)
}

const copyAddress = (address: string): void => {
  navigator.clipboard.writeText(address)
  ElMessage.success(t('复制成功'))
}

const getCryptoIcon = (symbol: string): string | undefined => {
  const cryptoList = [
    {
      symbol: 'USDT',
      icon: 'https://cryptologos.cc/logos/tether-usdt-logo.svg'
    }
  ]
  return cryptoList.find(c => c.symbol === symbol)?.icon
}

const handleAddSuccess = (item): void => {
  console.log(item,'item');
  walletAddressAdd(item).then(res => {
    ElMessage.success(t('地址添加成功'))
    fetchAddresses();
    })
}
//修改
const handleAddSuccess2 = (item): void => {

  walletAddressUpdate(item).then(res => {
    ElMessage.success(t('设置成功'))
    fetchAddresses();
  })
}

const handleBack = () => {
  if (fromAccount.value) {
    router.push('/account')
  } else {
    router.push('/assets')
  }
}

// 点击删除按钮
const handleDeleteClick = (item) => {

  // walletAddressdel({id:item.id}).then(res => {
  //   ElMessage.success(t('删除成功'))
  //   fetchAddresses();
  //   })
  addressToDelete.value = item.id
  showDeleteVerify.value = true
}
//点击修改
const handleDeleteClick2 = (idnumber) => {
  showAddDialog2.value = true;
  itemsuccess.value = idnumber;
  console.log(itemsuccess.value,'itemsuccess.value');

  // showDeleteVerify.value = true
}

// 验证通过后删除
const handleDeleteConfirm = async ({ type, code }: { type: string, code: string }) => {
  try {
    await walletAddressdel({id:addressToDelete.value,code:code})
    ElMessage.success(t('删除成功'))
    showDeleteVerify.value = false
    addressToDelete.value = null
    // 重新获取列表
    await fetchAddresses()
  } catch (error: any) {
    ElMessage.error(error.message || t('删除失败'))
  }
}
onMounted(() => {
  fetchAddresses();
})
</script>

<style lang="scss" scoped>
.wallet-container {
  background-color: #fff;
  min-height: 100vh;
  display: flex;
  flex-direction: column;
}

.page-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.wallet-page {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
  width: 100%;
}

.page-nav {
  margin-bottom: 20px;

  .breadcrumb {
    margin-bottom: 16px;

    :deep(.el-breadcrumb__item) {
      .el-breadcrumb__inner {
        color: #666;
        font-weight: normal;
        cursor: pointer;

        &:hover {
          color: #1890ff;
        }

        i {
          margin-right: 4px;
        }
      }
    }
  }

  .divider {
    height: 1px;
    background: #e8e8e8;
    margin: 0;
  }
}

.page-header {
  margin-bottom: 24px;

  h1 {
    font-size: 28px;
    color: #111;
    font-weight: 400;
    margin-bottom: 12px;
  }

  .security-alert {
    color: #0066c0;
    font-size: 14px;

    i {
      margin-right: 8px;
    }
  }
}

.action-bar {
  margin-bottom: 24px;
}

.address-list {
  display: grid;
  gap: 16px;
}
.pagination-wrapper {
  margin-top: 24px;
  margin-bottom: 24px;
  display: flex;
  justify-content: flex-end;
}

.address-card {
  background: #fff;
  border: 1px solid #ddd;
  border-radius: 8px;
  padding: 20px;
  transition: all 0.3s;

  &:hover {
    box-shadow: 0 2px 8px rgba(0,0,0,0.05);
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
    padding-bottom: 16px;
    border-bottom: 1px solid #eee;

    .crypto-info {
      display: flex;
      align-items: center;
      gap: 12px;

      .crypto-icon {
        width: 32px;
        height: 32px;
      }

      .crypto-name {
        font-size: 16px;
        font-weight: 500;
        color: #111;
      }
    }
  }

  .address-info {
    .network,
    .address,
    .remark {
      display: flex;
      align-items: center;
      margin-bottom: 12px;

      &:last-child {
        margin-bottom: 0;
      }

      .label {
        width: 60px;
        color: #666;
      }

      .value {
        flex: 1;
        color: #333;
        font-family: monospace;
      }
    }

    .address {
      word-break: break-all;
    }
  }
}

:deep(.amazon-button) {
  &.primary {
    background: linear-gradient(to bottom, #f7dfa5, #f0c14b);
    border-color: #a88734 #9c7e31 #846a29;
    color: #111;

    &:hover {
      background: linear-gradient(to bottom, #f5d78e, #eeb933);
    }
  }
}

:deep(.el-empty) {
  padding: 60px 0;

  .empty-icon {
    font-size: 80px;
    color: #ccc;
    margin-bottom: 20px;
  }

  .empty-text {
    margin-top: 20px;
    color: #666;
    font-size: 14px;
  }
}
</style>
